package com.tree.leetcode.common;

import java.util.Scanner;

/**
 * package com.tree.leecode
 * description:
 * 链表节点
 *
 * @author tree
 * @date 2020-03-04 17:23
 */
public class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int x) {
        val = x;
    }

    public ListNode(int x, ListNode next) {
        val = x;
        this.next = next;
    }

    /**
     * 组装Node
     * @return
     */
    public static ListNode nodeBuilder(){
        ListNode node = null;
        System.out.println("开始输入...");

        Scanner scanner = new Scanner(System.in);

        try {
            int input = Integer.valueOf(scanner.nextLine());
            node = new ListNode(input);
            while (scanner.hasNextLine()) {
                input = Integer.valueOf(scanner.nextLine());
                addNode(node,input);
            }
        }catch (Exception e){
            System.out.println("输入结束..."+e.getMessage());
        }
        return  node;
    }

    /**
     * 组装Node
     * @return
     */
    public static ListNode nodeBuilder(int[] array){

        if (array==null || array.length ==0) {
            return null;
        }
        ListNode node = new ListNode(array[0]);
        for (int i = 1; i < array.length; i++) {
            addNode(node ,array[i]);
        }

        return  node;
    }

    /**
     * 添加节点
     * @param head
     * @param val
     */
    public static void addNode(ListNode head, int val) {
        ListNode node = head;
        while (node.next != null) {
            node = node.next;
        }
        node.next = new ListNode(val);
    }

    /**
     * 打印结果
     * @param listNode
     */
    public static void printNodeResult(ListNode listNode){
        if(listNode != null ){
            StringBuilder sb = new StringBuilder(1024);
            sb.append(listNode.val).append(" ");
            while (listNode.next != null){
                listNode = listNode.next;
                sb.append(listNode.val).append(" ");
            }
            System.out.println("输出Node节点："+sb);
        }else {
            System.out.println("输出Node节点为空");
        }
    }

}
